package top.hcode.hoj.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.nutz.lang.Stopwatch;
import org.nutz.lang.Strings;
import org.nutz.lang.random.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Author: LiuLin
 * @Date: 2019/1/4 9:16
 */
@Aspect
@Component
public class RestLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(RestLogAspect.class);


    /**
     * 定义切入点，切入点为com.example.aop下的所有函数
     */
    @Pointcut("execution(public * top.hcode.hoj.controller..*.*(..))")
    public void webLog() {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Stopwatch stopwatch = Stopwatch.begin();
        String requestId = R.UU16().substring(0, 8);
        MDC.put("requestId", requestId);
        try {
            // 接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            // 记录下请求内容
            logger.info("{} {} {}{}, {}", getRemoteIpAddr(request), request.getMethod(),
                    request.getRequestURI(), Strings.isBlank(request.getQueryString()) ? "" : "?" + request.getQueryString(),
                    printArgs(joinPoint.getArgs()));
//            logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

            return joinPoint.proceed();
        } finally {
            stopwatch.stop();
            logger.info("used : {} ms", stopwatch.getDuration());
        }
    }

    private String printArgs(Object[] args) {
        return "[" +
                Arrays.stream(args)
                        .map(this::printArg)
                        .collect(Collectors.joining(", "))
                + "]";
    }

    private String printArg(Object arg) {
        if (arg == null) {
            return null;
        }

        if ( arg.getClass().isArray() ){
            return Arrays.toString((Object[]) arg);
        }

        Class<?> clazz = arg.getClass();
        if (clazz.getPackage() != null && clazz.getPackage().getName().startsWith("top.hcode")) {
            return arg.toString();
        }

        if (HttpServletRequest.class.isAssignableFrom(clazz) ||
                HttpServletResponse.class.isAssignableFrom(clazz) ||
                HttpSession.class.isAssignableFrom(clazz) ||
                MultipartFile.class.isAssignableFrom(clazz) ||
                Model.class.isAssignableFrom(clazz) ||
                ModelAndView.class.isAssignableFrom(clazz) ||
                RedirectAttributes.class.isAssignableFrom(clazz) ||
                BindingResult.class.isAssignableFrom(clazz)) {
            return clazz.getSimpleName();
        }
        return arg.toString();
    }

    public static String getRemoteIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        if (request != null) {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress)) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    assert inet != null;
                    ipAddress = inet.getHostAddress();
                }

            }

            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length() = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        }
        return ipAddress;
    }

}
